//
//  OtherOrderController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/6/15.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON
import ReachabilitySwift
//其它订单列表管理
class OtherOrderController:UIViewController{
    var interfaceUrl = ""//接口
    var dataUrl = "listdata"
    var carAuditArray: [CarAuditModel]!
    var driverAuditArray: [DriverAuditModel]!
    var drivingArray: [DrivingLicenseModel]!
    var licenseArray: [DriveLicenseModel]!
    var insureArray: [InsuranceModel]!
    var fineArray: [CarFineModel]!
    var mortgageArray: [MortgageModel]!
    var purchaseArray: [PurchaseModel]!
    var otherTable:UITableView!//数据表格
    override func viewDidLoad() {
        super.viewDidLoad()
        if("2" == isEmployee){
            if("1" == pageTag){
                dataUrl = "todolist"
            }else if ("2" == pageTag){
                dataUrl = "mydolist"
            }
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if "caraudit" == self.interfaceUrl {
           carAuditArray = Array<CarAuditModel>()
        }
        else if "drivelicenseaudit" == self.interfaceUrl {
           driverAuditArray = Array<DriverAuditModel>()
        }
        else if "drivinglicense" == self.interfaceUrl {
            drivingArray = Array<DrivingLicenseModel>()
        }
        else if "drivelicense" == self.interfaceUrl {
            licenseArray = Array<DriveLicenseModel>()
        }
        else if "carinsurance" == self.interfaceUrl {
            insureArray = Array<InsuranceModel>()
        }
        else if "carfine" == self.interfaceUrl {
            fineArray = Array<CarFineModel>()
        }
        else if "carmortgage" == self.interfaceUrl || "cartrade" == self.interfaceUrl{
            mortgageArray = Array<MortgageModel>()
        }
        else if "carpurchase" == self.interfaceUrl {
            purchaseArray = Array<PurchaseModel>()
        }
        //初始化表格
        otherTable = UITableView(frame: CGRect(x:0,y:kStatusBarH + kNavigationBarH + 40,width:kScreenW,height:kScreenH),style: UITableViewStyle.plain)
        otherTable?.delegate = self
        otherTable?.dataSource = self
        otherTable?.backgroundColor = tableBgColor
        otherTable?.separatorStyle = UITableViewCellSeparatorStyle.none
        otherTable?.rowHeight = 80
        self.view.addSubview(otherTable!)
        otherTable?.snp.makeConstraints({ (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(kStatusBarH + kNavigationBarH + 40)//选项卡高度 40
            make.bottom.equalTo(self.view).offset(-kTabBarH)
        })
        if reachability.isReachable {
            loadData()//查询列表
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
}
extension OtherOrderController{
    func loadData() {
        let urlString = "\(projectUrl)/order/other/\(dataUrl)/\(interfaceUrl)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
        Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
            if response.result.isSuccess{
                let json = JSON(response.result.value as! [String : AnyObject])
                if json["success"] == true {
                    for (_,orderJson) : (String,JSON) in json["rdata"] {
                        if "caraudit" == self.interfaceUrl {
                            let model = CarAuditModel.init(dict: orderJson)
                            self.carAuditArray.append(model)
                        }else if "drivelicenseaudit" == self.interfaceUrl {
                            let model = DriverAuditModel.init(dict: orderJson)
                            self.driverAuditArray.append(model)
                        }
                        else if "drivinglicense" == self.interfaceUrl {
                           let model = DrivingLicenseModel.init(dict: orderJson)
                            self.drivingArray.append(model)
                        }
                        else if "drivelicense" == self.interfaceUrl {
                            let model = DriveLicenseModel.init(dict: orderJson)
                            self.licenseArray.append(model)
                        }
                        else if "carinsurance" == self.interfaceUrl {
                            let model = InsuranceModel.init(dict: orderJson)
                            self.insureArray.append(model)
                        }
                        else if "carfine" == self.interfaceUrl {
                            let model = CarFineModel.init(dict: orderJson)
                            self.fineArray.append(model)
                        }
                        else if "carmortgage" == self.interfaceUrl || "cartrade" == self.interfaceUrl{
                            let model = MortgageModel.init(dict: orderJson)
                            self.mortgageArray.append(model)
                        }
                        else if "carpurchase" == self.interfaceUrl {
                            let model = PurchaseModel.init(dict: orderJson)
                            self.purchaseArray.append(model)
                        }
                    }
                    self.otherTable.reloadData()
                }
                else{
                    self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                }
            }
            else{
                print(response.result.error!) //输出错误日志
            }
        }
    }
    //登录失效 清除缓存
    func failOperNoticeFun(code:String,message:String){
        let alertController = UIAlertController(title: "通知", message: message, preferredStyle: .alert)
        if("000" == code){
            let okAction = UIAlertAction(title: "去登录", style: .default, handler:{
                (UIAlertAction) -> Void in
                if(PersonalModel.deletePersonal(userID: userID! as! String)){
                    let userDefault = UserDefaults.standard
                    userDefault.removeObject(forKey: "userID")
                    userDefault.removeObject(forKey: "tokenID")
                    userDefault.removeObject(forKey: "isEmployee")
                    let mainVC = UINavigationController(rootViewController: LoginController())
                    app.window?.rootViewController = mainVC
                }
            })
            alertController.addAction(okAction)
        }else{
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
        }
        self.present(alertController, animated: true, completion: nil)
    }
}
extension OtherOrderController:UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if "caraudit" == self.interfaceUrl {
            return carAuditArray.count
        }else if "drivelicenseaudit" == self.interfaceUrl {
            return driverAuditArray.count
        }
        else if "drivinglicense" == self.interfaceUrl {
            return drivingArray.count
        }
        else if "drivelicense" == self.interfaceUrl {
            return licenseArray.count
        }
        else if "carinsurance" == self.interfaceUrl {
            return insureArray.count
        }
        else if "carfine" == self.interfaceUrl {
            return fineArray.count
        }
        else if "carmortgage" == self.interfaceUrl || "cartrade" == self.interfaceUrl{
            return mortgageArray.count
        }
        else if "carpurchase" == self.interfaceUrl {
            return purchaseArray.count
        }
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell: OtherTableCell? = tableView.dequeueReusableCell(withIdentifier: "otherTableCellID") as? OtherTableCell
        if cell == nil {
            cell = OtherTableCell(style: UITableViewCellStyle.default,reuseIdentifier: "otherTableCellID")
        }
        if "caraudit" == self.interfaceUrl {
            if carAuditArray.count > 0 {
                let model = carAuditArray[(indexPath as NSIndexPath).row]
                let md = OtherModel.init(orderNo: model.orderNo, ostatus: model.ostatus, subUser: model.subUser, subTime: model.subtime, oprocess: model.oprocess, isOriginals: "",opeType: "oprocessOrder")
                cell?.configCellDateWithModel(md)
            }
        }
        else if "drivelicenseaudit" == self.interfaceUrl {
            if driverAuditArray.count > 0 {
                let model = driverAuditArray[(indexPath as NSIndexPath).row]
                let md = OtherModel.init(orderNo: model.orderNo, ostatus: model.ostatus, subUser: model.subUser, subTime: model.subtime, oprocess: model.oprocess, isOriginals: "",opeType: "oprocessOrder")
                cell?.configCellDateWithModel(md)
            }
        }
        else if "drivinglicense" == self.interfaceUrl {
            if drivingArray.count > 0 {
                let model = drivingArray[(indexPath as NSIndexPath).row]
                let md = OtherModel.init(orderNo: model.orderNo, ostatus: model.ostatus, subUser: model.subUser, subTime: model.subtime, oprocess: model.oprocess, isOriginals: model.isOriginals,opeType: "oprocessOrder")
                cell?.configCellDateWithModel(md)
            }
        }
        else if "drivelicense" == self.interfaceUrl {
            if licenseArray.count > 0 {
                let model = licenseArray[(indexPath as NSIndexPath).row]
                let md = OtherModel.init(orderNo: model.orderNo, ostatus: model.ostatus, subUser: model.subUser, subTime: model.subtime, oprocess: model.oprocess, isOriginals: model.isOriginals,opeType: "oprocessOrder")
                cell?.configCellDateWithModel(md)
            }
        }
        else if "carinsurance" == self.interfaceUrl {
            if insureArray.count > 0 {
                let model = insureArray[(indexPath as NSIndexPath).row]
                let md = OtherModel.init(orderNo: model.orderNo, ostatus: model.ostatus, subUser: model.subUser, subTime: model.subtime, oprocess: "", isOriginals: model.isOriginals,opeType: "insuranceOrder")
                cell?.configCellDateWithModel(md)
            }
        }
        else if "carfine" == self.interfaceUrl {
            if fineArray.count > 0 {
                let model = fineArray[(indexPath as NSIndexPath).row]
                let md = OtherModel.init(orderNo: model.orderNo, ostatus: model.ostatus, subUser: model.subUser, subTime: model.subtime, oprocess: "", isOriginals: "",opeType: "otherOrder")
                cell?.configCellDateWithModel(md)
            }
        }
        else if "carmortgage" == self.interfaceUrl || "cartrade" == self.interfaceUrl{
            if mortgageArray.count > 0 {
                let model = mortgageArray[(indexPath as NSIndexPath).row]
                let md = OtherModel.init(orderNo: model.orderNo, ostatus: model.ostatus, subUser: model.subUser, subTime: model.subtime, oprocess: "", isOriginals: "",opeType: "otherOrder")
                cell?.configCellDateWithModel(md)
            }
        }
        else if "carpurchase" == self.interfaceUrl {
            if purchaseArray.count > 0 {
                let model = purchaseArray[(indexPath as NSIndexPath).row]
                let md = OtherModel.init(orderNo: model.orderNo, ostatus: model.ostatus, subUser: model.subUser, subTime: model.subtime, oprocess: "", isOriginals: "",opeType: "otherOrder")
                cell?.configCellDateWithModel(md)
            }
        }
        cell?.selectionStyle = UITableViewCellSelectionStyle.default
        return cell!
    }
    //选中cell时触发这个代理
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: false)//点击完成，取消高亮
        if "caraudit" == self.interfaceUrl {
            let model = carAuditArray[(indexPath as NSIndexPath).row]
            let aic = AuditInfoController()
            aic.carAudit = model
            self.present(aic, animated: true, completion: nil)
        }else if "drivelicenseaudit" == self.interfaceUrl {
            let model = driverAuditArray[(indexPath as NSIndexPath).row]
            let dic = DriverInfoController()
            dic.driverInfo = model
            self.present(dic, animated: true, completion: nil)
        }
        else if "drivinglicense" == self.interfaceUrl {
            let model = drivingArray[(indexPath as NSIndexPath).row]
            let dic = DrivingInfoController()
            dic.drivingInfo = model
            self.present(dic, animated: true, completion: nil)
        }
        else if "drivelicense" == self.interfaceUrl {
            let model = licenseArray[(indexPath as NSIndexPath).row]
            let lic = LicenseInfoController()
            lic.licenseInfo = model
            self.present(lic, animated: true, completion: nil)
        }
        else if "carinsurance" == self.interfaceUrl {
            let model = insureArray[(indexPath as NSIndexPath).row]
            let iic = InsuranceInfoController()
            iic.insuranceInfo = model
            self.present(iic, animated: true, completion: nil)
        }
        else if "carfine" == self.interfaceUrl {
            let model = fineArray[(indexPath as NSIndexPath).row]
            let fic = FineInfoController()
            fic.fineInfo = model
            self.present(fic, animated: true, completion: nil)
        }
        else if "cartrade" == self.interfaceUrl{
            let model = mortgageArray[(indexPath as NSIndexPath).row]
            let mic = MortgageInfoController()
            mic.mortgage = model
            mic.orderType = "cartrade"
            mic.appTitle = "二手车买卖"
            self.present(mic, animated: true, completion: nil)
        }else if  "carmortgage" == self.interfaceUrl {
            let model = mortgageArray[(indexPath as NSIndexPath).row]
            let mic = MortgageInfoController()
            mic.mortgage = model
            mic.orderType = "carmortgage"
            mic.appTitle = "抵押贷款"
            self.present(mic, animated: true, completion: nil)
        }
        else if "carpurchase" == self.interfaceUrl {
            let model = purchaseArray[(indexPath as NSIndexPath).row]
            let pic = PurchaseInfoController()
            pic.purchase = model
            self.present(pic, animated: true, completion: nil)
        }
    }
}
